package com.xinongbest.oa.controller;

import com.alibaba.fastjson.JSON;
import com.xinongbest.oa.entity.LeaveForm;
import com.xinongbest.oa.entity.User;
import com.xinongbest.oa.service.LeaveFormService;
import com.xinongbest.oa.service.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "LeaveFormServlet", urlPatterns = "/leave/*")
public class LeaveFormServlet extends HttpServlet {

    private LeaveFormService leaveFormService = new LeaveFormService();

    private Logger logger = LoggerFactory.getLogger(LeaveFormService.class);

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        String requestURI = request.getRequestURI();
        String method = requestURI.substring(requestURI.lastIndexOf("/") + 1);
        if ("create".equals(method)) {
            this.create(request, response);
        } else if ("list".equals(method)) {
            this.getLeaveFormList(request, response);
        } else if ("audit".equals(method)) {
            this.audit(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    /**
     * 创建请假申请单
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void create(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 处理请求参数
        HttpSession session = request.getSession();
        User login_user = (User) session.getAttribute("login_user");
        LeaveForm leaveForm = new LeaveForm();
        String formType = request.getParameter("formType");
        String startDate = request.getParameter("startTime");
        String endDate = request.getParameter("endTime");
        String reason = request.getParameter("reason");
        Map<String, String> result = new HashMap<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH");
        try {
            leaveForm.setEmployeeId(login_user.getEmployeeId());
            leaveForm.setFormType(Integer.parseInt(formType));
            leaveForm.setStartTime(dateFormat.parse(startDate));
            leaveForm.setEndTime(dateFormat.parse(endDate));
            leaveForm.setReason(reason);
            leaveForm.setCreateTime(new Date());
            // 调用业务逻辑
            leaveFormService.createLeaveForm(leaveForm);
            result.put("code", "0");
            result.put("message", "success");
        } catch (Exception e) {
            logger.error("请假申请异常", e);
            result.put("code", e.getClass().getSimpleName());
            result.put("message", e.getMessage());
        }
        // 响应请求
        String json = JSON.toJSONString(result);
        response.getWriter().println(json);
    }

    /**
     * <h2>获取待审批请假流程</h2>
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void getLeaveFormList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("login_user");
        List<Map<String, Object>> leaveFormList = leaveFormService.getLeaveFormList("process", user.getEmployeeId());
        Map<String, Object> result = new HashMap<>();
        result.put("code", "0");
        result.put("msg", "");
        result.put("count", leaveFormList.size());
        result.put("data", leaveFormList);
        response.getWriter().println(JSON.toJSONString(result));
    }

    public void audit(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String formId = request.getParameter("formId");
        String result = request.getParameter("result");
        String reason = request.getParameter("reason");
        User login_user = (User) request.getSession().getAttribute("login_user");
        Map<String, String> res = new HashMap<>();
        try {
            leaveFormService.audit(Long.parseLong(formId), login_user.getEmployeeId(), result, reason);
            res.put("code", "0");
            res.put("msg", "success");
        } catch (Exception e) {
            logger.error("请假审批审核失败");
            res.put("code", e.getClass().getSimpleName());
            res.put("msg", e.getMessage());
        }
        response.getWriter().println(JSON.toJSONString(res));
    }
}
